﻿using DimensionsHelper.Client.WinUi.Contracts;

namespace DimensionsHelper.Client.WinUi.Models;

public partial class StringMap : IStringMap
{
    private readonly Dictionary<string, string> _innerMap = [];


    public int Count => _innerMap.Count;


    public IEnumerator GetEnumerator() => _innerMap.Values.GetEnumerator();


    public string[] GetKeys() => _innerMap.Keys.ToArray();


    public string? GetValue(string? key)
    {
        return string.IsNullOrEmpty(key) ? null : _innerMap.GetValueOrDefault(key);
    }


    public static StringMap FromDataRow(DataRow row)
    {
        StringMap map = new();

        foreach (DataColumn column in row.Table.Columns)
        {
            string colName = column.ColumnName;
            string data = row[column]?.ToString() ?? "";

            if (!map._innerMap.TryAdd(colName, data))
            {
                map._innerMap[colName] = data;
            }
        }

        return map;
    }


    public static StringMapCollection BuildCollection(DataTable source)
    {
        List<StringMap> list = [];
        List<string> headers = [];

        foreach (DataColumn? column in source.Columns.OfType<DataColumn>())
        {
            headers.Add(column.ColumnName);
        }

        foreach (DataRow row in source.Rows)
        {
            list.Add(FromDataRow(row));
        }

        return new StringMapCollection(list, headers);
    }
}